<template>
    <view class="login" :style="{ direction: $store.state.dir }">
        <!-- <logo></logo> -->
        <view class="logo">
            <image src="/static/login/logo.png"></image>
            <text> haloهالو</text>
        </view>
        <!-- <input-item :name="$t('login.username')" icon="icon-user">
			<input v-model="name" class="input" type="text" />
		</input-item>
		<input-item :name="$t('login.password')" icon="icon-unlock">
			<input v-model="password" class="input" type="text" password />
		</input-item> -->
        <view class="login_ul">
            <ul>
                <li>
                    <image src="/static/login/icon_03.png"></image>
                    <text>*</text>
                    <input
                        v-model="phone"
                        :placeholder="$t('login.phone')"
                        placeholder-style="color: #9E6B47;"
                        type="text"
                    />
                </li>
                <li>
                    <image src="/static/login/icon_04.png"></image>
                    <text>*</text>
                    <input
                        v-model="code"
                        placeholder="Verification code"
                        placeholder-style="color: #9E6B47;"
                        type="text"
                    />
                    <view
                        class="login_code"
                        @click.stop="handleCode"
                        :style="{ opacity: isCounting ? '0.7' : '1' }"
                    >
                        {{ countdownText }}
                    </view>
                </li>
            </ul>
            <view class="login-agreement">
                <view class="login-left" @click.stop="handleIsCheck">
                    <image
                        src="@/static/business/check.png"
                        v-if="isCheck"
                    ></image>
                    <image src="@/static/business/off.png" v-else></image>
                </view>
                <view class="login-right">
                    <!-- @click.stop="handleUser"  @click.stop='handlePrivary'-->
                    I have read and agree<span @click.stop="handleUser"
                        >《User Agreement》</span
                    >and<span @click.stop="handlePrivary"
                        >《Privacy Policy》</span
                    >
                </view>
            </view>
        </view>
        <view class="login-button">
            <u-button
                @click="handleLogin"
                style="background: #fa751f; color: #fff"
                size="large"
                shape="circle"
                :text="$t('login.loginBtn')"
            ></u-button>
            <!-- <br />
			<view>
				<u-button @click="auth"  icon="google" size="large" shape="circle"
					:text="$t('login.loginBtnGoogle')"></u-button>
			</view> -->
            <!-- <u-divider text="Or"></u-divider> -->
            <!-- <p>Forgot password</p> -->
            <u-button
                @click="PasswordLogin"
                type="primary"
                size="large"
                shape="circle"
                plain=""
                text="PasswordLogin"
            ></u-button>
            <u-button
                class="btn"
                @click="handleRegButton2"
                size="large"
                shape="circle"
                :text="$t('login.regBtn')"
            ></u-button>
        </view>
    </view>
</template>

<script>
import { APP_ROLE, CurrentRole } from "../../config";
import { showFailure, showMessage, showSuccess } from "../../lib/helper";
import { getSendSms, getLoginBySms } from "@/lib/business";
import { login, googleLogin } from "../../lib/service";
import { client, isValidEgyptianPhoneNumber } from "../../utils/utils";
import { emConnect } from "@/EaseIM/emApis";
export default {
    data() {
        return {
            name: "",
            password: "",
            phone: "",
            code: "",
            isCheck: false,
            isCounting: false, // 是否正在倒计时
            countdown: 60, // 倒计时秒数
            timer: null, // 定时器引用
            isRotate: false, //是否加载旋转
            isFocus: true, // 是否聚焦
            client_id:
                "412561318887-u244ikgmdlu1b89ntn7oqvh4aafh2bfi.apps.googleusercontent.com",
            client_secret: "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",
        };
    },
    mounted() {},
    onLoad(options) {
        // this.getUserInfo(options)
    },
    beforeDestroy() {
        // 组件销毁前清除定时器
        if (this.timer) {
            clearInterval(this.timer);
        }
    },
    computed: {
        countdownText() {
            return this.isCounting ? `${this.countdown}S` : "Get";
        },
    },
    methods: {
        // 开始倒计时
        handleCode() {
            let _this = this;
            if (this.isCounting) return;
            if (!this.phone) {
                showMessage("Please provide your contact phone number");
                return;
            }
            let isPhone = isValidEgyptianPhoneNumber(_this.phone);
            if (!isPhone) {
                showMessage(this.$t("message.phone.wrong"));
                return;
            }
            getSendSms({
                mobile: _this.phone,
            })
                .then((res) => {
                    // 开始倒计时
                    _this.startCountdown();
                })
                .catch((res) => {
                    showFailure(this.$t("message.sendCode.failed"));
                });
        },
        startCountdown() {
            this.isCounting = true;
            this.countdown = 60;
            this.timer = setInterval(() => {
                if (this.countdown > 0) {
                    this.countdown--;
                } else {
                    this.stopCountdown();
                }
            }, 1000);
        },
        stopCountdown() {
            this.isCounting = false;
            if (this.timer) {
                clearInterval(this.timer);
                this.timer = null;
            }
        },
        handleUser() {
            uni.navigateTo({
                url: "/pages/login/agreement/userAgreement",
            });
        },
        handlePrivary() {
            uni.navigateTo({
                url: "/pages/login/agreement/privacyPolicy",
            });
        },
        PasswordLogin() {
            uni.navigateTo({
                url: "/pages/login/loginPassword",
            });
        },
        // getUserInfo(options) {
        // 	let _this = this;
        // 	let code = ''
        // 	// #ifdef APP-PLUS
        // 	code = options.code
        // 	// #endif
        // 	// #ifdef H5
        // 	const urlParams = new URLSearchParams(window.location.search);
        // 	code = urlParams.get('code');
        // 	// #endif
        // 	if (!code) {
        // 		return;
        // 	}
        // 	// 用授权码交换访问令牌地址
        // 	const tokenEndpoint = 'https://oauth2.googleapis.com/token';
        // 	const requestBody = new URLSearchParams();
        // 	requestBody.append('code', code);
        // 	// 你的 Google OAuth 客户端 ID
        // 	requestBody.append('client_id', this.client_id);
        // 	// 你的Google OAuth 客户端密钥
        // 	requestBody.append('client_secret', this.client_secret);
        // 	requestBody.append('redirect_uri', 'https://anta123.com/pages/login/login');
        // 	requestBody.append('grant_type', 'authorization_code'); //这些参数在之前配置的有，看前面的代码
        // 	fetch(tokenEndpoint, {
        // 			method: 'POST',
        // 			headers: {
        // 				'Content-Type': 'application/x-www-form-urlencoded',
        // 			},
        // 			body: requestBody
        // 		})
        // 		.then(response => response.json())
        // 		.then(data => {
        // 			// 获得token令牌的信息
        // 			const accessToken = data.access_token;
        // 			// 调用获取用户信息接口
        // 			fetch('https://www.googleapis.com/oauth2/v2/userinfo', {
        // 					headers: {
        // 						Authorization: `Bearer ${accessToken}`
        // 					}
        // 				})
        // 				.then(response => response.json())
        // 				.then(userInfo => {
        // 					const {
        // 						name,
        // 						email,
        // 						picture,
        // 						id: googleid
        // 					} = userInfo
        // 					const params = {
        // 						name,
        // 						email,
        // 						picture,
        // 						googleid
        // 					}
        // 					uni.showLoading();
        // 					_this.handleGoogleLogin(params)

        // 				})

        // 		})
        // },
        // handleGoogleLogin(params){
        // 	googleLogin(params).then(res => {
        // 		uni.hideLoading();
        // 		showSuccess();
        // 		this.$store.dispatch('setUser', {
        // 			...res.data.user,
        // 			token: res.data.token,
        // 			imtoken: res.data.imtoken,
        // 			impass: res.data.impass,
        // 			imuser: res.data.imuser
        // 		});
        // 		// uni.navigateBack()
        // 		uni.switchTab({
        // 			url: "/pages/index/index"
        // 		})
        // 		if (res.data && res.data.imtoken) {
        // 			this.loginWithPhoneNumber(res.data)
        // 		}
        // 	}).catch((err) => {
        // 		uni.hideLoading();
        // 		showFailure();
        // 	});
        // },
        // auth() {
        // 	let _this = this;
        // 	// 你的Google OAuth 客户端 ID
        // 	const clientId = this.client_id;
        // 	// 重定向 URI
        // 	const redirectUri = 'https://anta123.com/pages/login/login';
        // 	// 请求的权限范围，可以根据需求修改
        // 	const scope = 'email profile';
        // 	// 用于防止跨站请求伪造（CSRF）攻击，可以不设置，可以随心设置
        // 	const state = '';
        // 	// 授权响应类型，表示要求返回授权码
        // 	const responseType = 'code';
        // 	const grantType = 'authorization_code';
        // 	//&prompt=login 把它加到window.authUrl的末尾可以让用户每次都需要重新输入账号和密码
        // 	const authUrl =
        // 		`https://accounts.google.com/o/oauth2/v2/auth?client_id=${clientId}&redirect_uri=${redirectUri}&scope=${scope}&state=${state}&response_type=${responseType}`;
        // 	//点击Google登录  执行这个方法进行跳转
        // 	console.log(authUrl,'authUrl')
        // 	// #ifdef APP-PLUS
        // 	uni.login({
        // 		provider: 'google',
        // 		scopes: 'profile email',
        // 		success: function(loginRes) {
        // 			console.log('loginRes////////', loginRes)
        // 			var access_token = loginRes.authResult.access_token;
        // 			// 登录成功
        // 			if (loginRes.errMsg === 'login:ok') {
        // 				uni.getUserInfo({
        // 					provider: 'google',
        // 					success: function(info) {
        // 						let googleid = info.userInfo.openid;
        // 						let {
        // 							name,
        // 							email,
        // 							picture
        // 						} = info.userInfo;
        // 						const params = {
        // 							name,
        // 							email,
        // 							picture,
        // 							googleid
        // 						}
        // 						uni.showLoading();
        // 						_this.handleGoogleLogin(params)
        // 					},
        // 					fail: function(err) {
        // 						// 获取用户信息失败
        // 						// err.code是错误码
        // 						uni.showToast({
        // 							title: `获取用户信息失败-错误码${JSON.stringify(err)}`,
        // 							icon: "none",
        // 							duration: 2000,
        // 						});
        // 					}
        // 				})
        // 			} else {
        // 				uni.showToast({
        // 					icon: 'none',
        // 					title: '登录授权失败: ' + JSON.stringify(loginRes),
        // 				});
        // 			}
        // 		},
        // 		fail: function(err) {
        // 			// 登录授权失败
        // 			// err.code是错误码
        // 			uni.showToast({
        // 				title: `登录连接失败-错误码${err.code}`,
        // 				icon: "none",
        // 				duration: 2000,
        // 			});
        // 		}
        // 	});
        // 	// #endif
        // 	// #ifdef H5
        // 	window.location.href = authUrl
        // 	// #endif
        // },
        handleIsCheck() {
            this.isCheck = !this.isCheck;
        },
        // 短信验证码登录
        handleLogin() {
            if (!this.isCheck) {
                showMessage("Please check the agreement first");
                return;
            }
            // getLoginBySms
            if (this.isRotate) {
                //判断是否加载中，避免重复点击请求
                return false;
            }
            if (!this.phone) {
                showMessage(this.$t("message.emety.phone"));
                return;
            }
            if (!this.code) {
                showMessage(this.$t("message.emety.code"));
            }
            uni.showLoading();
            getLoginBySms({
                phone: this.phone,
                vcode: this.code,
            })
                .then((res) => {
                    uni.hideLoading();
                    showSuccess();
                    this.$store.dispatch("setUser", {
                        ...res.data.user,
                        token: res.data.token,
                        imtoken: res.data.imtoken,
                        impass: res.data.impass,
                        imuser: res.data.imuser,
                    });

                    if (res.data && res.data.imtoken) {
                        this.loginWithPhoneNumber(res.data);
                    } else {
                        // this.handleBack();
                        uni.switchTab({
                            url: "/pages/index/index",
                        });
                    }
                })
                .catch((err) => {
                    uni.hideLoading();
                    showFailure();
                });
        },
        handleBack() {
            const pages = getCurrentPages();
            if (pages && pages.length > 1) {
                // 有上一页则返回上一页
                uni.navigateBack({
                    delta: 1,
                });
            } else {
                // 没有上一页则跳转到首页
                uni.switchTab({
                    url: "/pages/index/index",
                });
            }
        },
        // handleLogin() {
        // 	if (this.isRotate) {
        // 		//判断是否加载中，避免重复点击请求
        // 		return false;
        // 	}
        // 	if (this.name.length <= 0) {
        // 		showMessage(this.$t('message.emety.username'));
        // 		return;
        // 	}
        // 	if (this.password.length <= 0) {
        // 		showMessage(this.$t('message.emety.password'));
        // 		return;
        // 	}

        // 	uni.showLoading();
        // 	login({
        // 			name: this.name,
        // 			password: this.password,
        // 			client,
        // 			im: 1
        // 		})
        // 		.then((res) => {
        // 			uni.hideLoading();
        // 			showSuccess();
        // 			this.$store.dispatch('setUser', {
        // 				...res.data.user,
        // 				token: res.data.token,
        // 				imtoken: res.data.imtoken,
        // 				impass: res.data.impass,
        // 				imuser: res.data.imuser
        // 			});

        // 			if (res.data && res.data.imtoken) {
        // 				this.loginWithPhoneNumber(res.data)
        // 			} else {
        // 				uni.navigateBack({
        // 					delta: 1,
        // 				})
        // 			}
        // 		})
        // 		.catch((err) => {
        // 			uni.hideLoading();
        // 			showFailure();
        // 		});
        // },
        async loginWithPhoneNumber(data) {
            const { loginWithAccessToken, closeEaseIM } = emConnect();
            loginWithAccessToken(data.imuser, data.imtoken);
            this.$store.commit("SET_LOGIN_USER_BASE_INFOS", {
                imuser: data.imuser,
                impass: data.impass,
            });
            this.setEMUserLoginInfosToStorage(data.imuser, data.imtoken);
        },
        setEMUserLoginInfosToStorage(imuser, imtoken) {
            const params = {
                key: `EM_LOGIN_INFOS`,
                data: {
                    imuser,
                    imtoken,
                },
            };
            this.handleBack();
            uni.setStorage({
                ...params,
            });
        },
        handleRegButton1() {
            uni.navigateTo({
                url: "/pages/login/register?type=1",
            });
        },
        handleRegButton2() {
            uni.navigateTo({
                url: "/pages/login/register?type=2",
            });
        },
        handleRegButton3() {
            uni.navigateTo({
                url:
                    "/pages/login/register?type=" +
                    (CurrentRole == APP_ROLE.Agent ? "2" : "1"),
            });
        },
    },
};
</script>

<style lang="scss" scoped>
.login-agreement {
    width: 100%;
    display: flex;
    align-items: center;
    padding: 0;
}

.login-agreement .login-left {
    display: flex;
    align-items: center;
}

.login-agreement .login-left image {
    width: 36rpx;
    height: 36rpx;
}

.login-agreement .login-left font {
    width: 32rpx;
    height: 32rpx;
    background: #ffffff;
    border: 2rpx solid #ececec;
    border-radius: 50%;
}

.login-agreement .login-right {
    padding-left: 20rpx;
    font-size: 24rpx;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #999999;
    line-height: 32rpx;
}

.login-agreement .login-right span {
    display: inline-block;
    color: #0075ff;
}

.login {
    padding: 0 30px;

    .login-button {
        margin-top: 20px;

        p {
            text-align: center;
            font-family: Manrope, Manrope;
            font-weight: 500;
            font-size: 28rpx;
            color: #666666;
            margin-top: 60rpx;
        }

        .btn {
            //margin-top: 33vh;
            font-family: Manrope, Manrope;
            font-weight: 500;
            font-size: 32rpx;
            color: #1c120d;
        }
    }
}

.logo {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 70rpx;

    image {
        width: 70rpx;
        height: 84rpx;
    }

    text {
        display: inline-block;
        font-size: 40rpx;
        color: red;
        font-weight: bold;
    }
}

.login_ul {
    margin-top: 80rpx;

    ul {
        li {
            height: 96rpx;
            border-radius: 60rpx;
            border: 2rpx solid #e8d9cf;
            display: flex;
            align-items: center;
            padding: 0 38rpx;
            margin-bottom: 44rpx;
            position: relative;

            image {
                width: 36rpx;
                height: 36rpx;
            }

            text {
                color: red;
            }

            input {
                display: inline-block;
                margin-left: 8rpx;
                font-size: 32rpx;
                color: #9e6b47;
            }

            .login_code {
                position: absolute;
                right: 30rpx;
                color: #fc721a;
            }
        }
    }
}
</style>
